<!--
*  2021-03-15
*  获取员工登录列表
-->
<template>
  <div id="app" class="login" tabindex="-1" ref="tabDiv">
    <!-- 头部导航 -->
    <van-nav-bar>
      <template slot="left">
        <van-icon name="arrow-left" @click="onClickLeft">返回扫码</van-icon>
        <van-button type="info" @click="onClickLogin(5)">更改重量</van-button>
      </template>
      <template slot="title">
        <div>
          <span v-show="loomNo">{{ loomNo }}织机</span>
          <span>任务过程图</span>
        </div>
      </template>
      <template slot="right">
        <van-button type="info" @click="onClickLogin(2)"
          >查看环节数据</van-button
        >
        <!-- <van-button type="danger" @click="onClickLogin(3)">更换纱线</van-button> -->
        <van-button type="danger" @click="onClickLogin(4)"
          >穿棕/打结</van-button
        >
      </template>
    </van-nav-bar>
    <div class="login-btn">
      <div class="login-btn__logo">
        <van-cell-group v-for="(task, key) in taskStep" :key="key">
          <van-button
            v-for="(step, index) in task.steps"
            :key="index"
            :class="
              step.status === 2 ? 'active' : step.status === 0 ? 'finish' : ''
            "
            >{{ step.name }}</van-button
          >
          <i :class="'line' + 0"></i>
          <i :class="'line' + 1"></i>
          <i :class="'line' + 2"></i>
        </van-cell-group>
      </div>
      <van-button @click="onClickLogin(1)" class="login-btn__login"
        >扫码登陆</van-button
      >
    </div>
    <!-- 登陆弹窗提示 -->
    <van-dialog
      v-model="show"
      :title="title"
      show-cancel-button
      confirm-button-text="登陆"
      @cancel="onClickCancel"
      @confirm="onGetLoginConfirm"
    >
      <van-cell title="姓名" :value="realName" />
      <van-cell title="手机号" :value="mobile" />
    </van-dialog>

    <!-- 坯布重量 -->
    <van-dialog
      v-model="isShow"
      title="坯布重量修正"
      show-cancel-button
      confirm-button-text="确认更改"
      @cancel="onClickCancel"
      @confirm="onConfirmWeight"
    >
      <van-field v-model="weight" placeholder="请输入修正后重量" clearable />
    </van-dialog>
  </div>
</template>

<script>
import { getInit } from "@/api/login";
import { getTaskStep } from "@/api/login";
import {
  getTaskAccept,
  getTaskAcceptNext,
  getTaskStepName,
  getTaskStepList,
  getWeavingByLoom,
  getWeavingClothByStepNo,
  getGreyClothWeight,
} from "@/api/warping";
import { randomStr, openWin, getFloat } from "@/utils/index";
import { removeInfo, setWeight, setErrorWeight } from "@/utils/auth";
import dayjs from "dayjs";
import {loadWeavingCraftDetailByCraftData} from "@/utils/weaving";
import {SPLIT_BLANK} from "@/utils/enum";
export default {
  name: "Login",
  data() {
    return {
      loginList: [],
      resUrl: "",
      params: {},
      subResIds: [],
      doingResUrl: "",
      demo: null,
      show: false,
      no: "",
      realName: "",
      mobile: "",
      title: "",
      id: "",
      taskStep: [],
      searchLoginList: [],
      taskId: "",
      printMac: "",
      metreMac: "",
      pos: {},
      code: "",
      lastTime: "",
      nextTime: "",
      lastCode: "",
      nextCode: "",
      loginInfo: "",
      loading: false,
      active: 0,
      printLen: 0,
      loomNo: "",
      flag: true,
      showPicker: false,
      currWeight: "",
      ip: "",
      greyClothId: "",
      isShow: false,
      weight: "",

      /* 扫码的 */
      scanCode: SPLIT_BLANK,
    };
  },
  watch: {
    // 监听工号
    id(no) {
      this.searchLoginList = this.loginList.filter(
        (item) => item.no.toString().indexOf(no) != -1
      );
    },
  },
  mounted() {
    removeInfo();
    const that = this;

    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn();
      });
    } else {
      window.apiready = function () {
        that.initFn();
      };
    }
  },
  methods: {
    initFn() {
      const that = this;
      that.loginList = window.api.pageParam.loginList;
      that.resUrl = window.api.pageParam.resUrl;
      that.taskId = window.api.pageParam.taskId;
      that.ip = window.api.pageParam.ip;
      that.greyClothId = window.api.pageParam.greyClothId;
      that.scanCode = window.api.pageParam.scanCode;
      that.demo = window.api.require("xGprinterPlus");
      that.onGetTaskStepName();
      that.onGetWeavingByLoom();
      that.onGetInit();
      // 监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewdisappear",
      }, function () {
        window.removeEventListener("keydown", that.onClickKeydown);
        window.api.closeWin();
      });
    },
    // 获取当前名称
    onGetTaskStepName() {
      getTaskStepName(
        {
          taskId: this.taskId,
        },
        (res) => {
          this.taskStep = res;
        }
      );
    },
    // 获取织机号
    onGetWeavingByLoom() {
      getWeavingByLoom(
        {
          taskId: this.taskId,
        },
        (res) => {
          this.loomNo = res;
        }
      );
    },
    // 扫码
    onClickLeft() {
      openWin("index");
    },
    // 获取焦点 扫码
    onClickLogin(flag) {
      this.loading = false;
      if (!this.loading) {
        this.flag = flag;
        this.onWatchEnter();
        this.loading = true;
        this.loginInfo = "";
        this.$toast({
          type: "loading",
          message: "请扫码",
          forbidClick: true,
          duration: 20000,
        });
      }
    },
    // 监听扫码时间
    onWatchEnter() {
      this.code = "";
      this.lastTime = "";
      this.nextTime = "";
      this.lastCode = "";
      this.nextCode = "";
      window.addEventListener("keydown", this.onClickKeydown);
    },
    // 监听事件
    onClickKeydown(e) {
      const that = this;
      if (!that.show) {
        that.$toast({
          type: "loading",
          message: "二维码解析中",
          forbidClick: true,
          duration: 20000,
        });
        if (window.event) {
          // IE
          that.nextCode = e.keyCode;
        } else if (e.which) {
          // Netscape/Firefox/Opera
          that.nextCode = e.which;
        }
        if (e.which === 13) {
          if (that.code.length < 3) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
          that.$refs.tabDiv.focus();
          that.$toast.clear();
          window.removeEventListener("keydown", that.onClickKeydown);
          console.log(dayjs().valueOf(), "扫码结束");
          that.loginInfo = that.code.replace(/Shift/g, "");
          if (that.loading) {
            let loginIndex = that.loginInfo.indexOf(",type=login,");
            if (loginIndex == -1) {
              that.$toast.fail("二维码异常");
              return false;
            }
            let no = that.loginInfo.substr(0, loginIndex);
            let pwd = that.loginInfo.substr(
              loginIndex + 12,
              that.loginInfo.length - 1
            );
            let index = that.loginList.findIndex((item) => item.no === no);
            if (index == -1) {
              that.$toast.fail("请联系管理员配置权限");
              return false;
            }
            that.$toast({
              type: "loading",
              message: "获取登陆信息",
              duration: 1000,
              onClose: () => {
                that.loginInfo = "";
                that.onGetLogin({
                  no: no,
                  realName: that.loginList[index].realName,
                  mobile: that.loginList[index].mobile,
                  pwd: pwd,
                });
              },
            });
          }
          that.code = "";
          that.lastCode = "";
          that.lastTime = "";
          return;
        }
        that.nextTime = new Date().getTime();
        if (!that.lastTime && !that.lastCode) {
          console.log(dayjs().valueOf(), "扫码开始。。。");
          that.code += e.key;
        }
        if (
          that.lastCode &&
          that.lastTime &&
          that.nextTime - that.lastTime > 500
        ) {
          // 当扫码前有keypress事件时,防止首字缺失
          that.code = e.key;
        } else if (that.lastCode && that.lastTime) {
          that.code += e.key;
        }
        that.lastCode = that.nextCode;
        that.lastTime = that.nextTime;
      }
    },
    isJSON(str) {
      let obj = "";
      if (typeof str == "string") {
        try {
          obj = JSON.parse(str);
          return obj;
        } catch (e) {
          return false;
        }
      }
      return obj;
    },
    // 点击 登录
    onGetLogin(list) {
      const that = this;
      that.no = list.no;
      that.title = "确认" + list.no + "登陆? ";
      that.realName = list.realName;
      that.mobile = list.mobile;
      that.pwd = list.pwd;
      that.show = true;
    },
    // 登录
    onGetLoginConfirm() {
      window.removeEventListener("keydown", this.onClickKeydown);
      const that = this;
      let param = {
        no: that.no,
        pwd: that.pwd,
        platform: 2,
        captcha: randomStr(),
      };
      if (that.printMac) {
        that.$store.dispatch("user/login", param).then(() => {
          if (that.flag === 1) {
            // 登录成功  扫码返回信息
            getTaskStep(
              {
                resUrl: that.resUrl,
              },
              (res) => {
                that.doingResUrl = res[0].doingResUrl;
                // 报工
                that.params = {
                  stepId: res[0].id,
                  flowType: res[0].flowType,
                  resId: res[0].resId,
                  stepNo: res[0].stepNo,
                  taskId: res[0].taskId,
                  resUrl: res[0].resUrl,
                  nextResUrl: res[0].doingResUrl,
                  nextStepNo: res[0].nextStepNo,
                  todoResUrl: res[0].todoResUrl,
                  doingResUrl: res[0].doingResUrl,
                  stepName: res[0].stepName,
                  nextStepName: res[0].nextStepName,
                  qrCode: that.resUrl,
                  status: res[0].status,
                  title: res[0].title,
                  scanCode: that.scanCode,
                };
                if (that.params.stepNo === 7 && that.params.flowType === 1) {
                  if (res[0].status === 1) {
                    // 接单
                    let obj = {
                      stepNo: that.params.stepNo,
                      taskId: that.params.taskId,
                    };
                    getTaskAccept(obj, () => {
                      // 打印
                      openWin("yarn", that.params);
                    });
                  } else {
                    // 已接单
                    openWin("yarn", that.params);
                  }
                } else {
                  if (that.params.stepNo === 16) {
                    // 胚布子流程
                    // that.connectBleByMacAddress(res[0].status, 1);
                    // that.isEnabledBluetooth(res[0].status, 1);
                    if (res[0].status === 1) {
                      // 接单
                      that.onGetTaskAcceptNext();
                    }
                  } else {
                    if (res[0].status === 1) {
                      // 接单
                      that.onGetTaskAccept(that.params);
                    } else {
                      // 已接单
                      if (res[0].flowType === 3 && res[0].stepNo === 3) {
                        openWin("checkCloth", that.params);
                      } else if (res[0].flowType === 3 && res[0].stepNo === 4) {
                        // 修布
                        if (that.ip == "192.168.66.115") {    //验布工位台
                          let serial = window.api.require("serialPort");
                          serial.examine(function (ret) {
                            if (ret.code) {
                              serial.openRead(
                                {
                                  com: "/dev/ttyS3", //串口地址
                                  rate: 9600, //波特率
                                  delay: 500, //RX延时 此参数能让数据返回完整单位毫秒（具体设置大小自测）
                                  hex: false, //返回数据类型 false:text  true:hex
                                },
                                function (ret) {
                                  if (ret.code && ret.data) {
                                    let respon = ret.data.replace(/\n\r/g, " ");
                                    serial.close(function (ret) {
                                      let res = respon.split("=");
                                      let resultWeight = [
                                        ...new Set(res),
                                      ].filter((item) => item !== "")[0];
                                      that.currWeight = that.reverse_a_number(resultWeight).replace(/\b(0+)/gi, "");

                                      setWeight(getFloat(that.currWeight, 2));
                                      openWin("warping", that.params);
                                      // 获取重量自动提交
                                      if (ret.code) {
                                        // 关闭
                                        console.log("关闭成功");
                                      }
                                    });
                                  }
                                }
                              );
                            } else {
                              that.$toast({
                                type: "fail",
                                message: "重量获取失败，请重新扫码",
                                onClose: () => {
                                  openWin("index");
                                },
                              });
                            }
                          });
                        } else {
                          openWin("warping", that.params);
                        }
                      } else {
                        if (
                          res[0].flowType === 2 &&
                          (res[0].stepNo === 2 ||
                            res[0].stepNo === 4 ||
                            res[0].stepNo === 6 ||
                            res[0].stepNo === 11 ||
                            res[0].stepNo === 15 ||
                            res[0].stepNo === 21 ||
                            res[0].stepNo === 22)
                        ) {
                          openWin("group-leader", that.params);
                        } else {
                          openWin("warping", that.params);
                        }
                      }
                    }
                  }
                }
              }
            );
          } else if (that.flag === 2) {
            // 历史环节数据
            that.onClickRight();
          } else if (that.flag === 3) {
            // 更换纬纱
            openWin("yarn-change", {
              taskId: this.taskId,
              greyClothId: this.greyClothId,
            });
          } else if (that.flag === 4) {
            // 登录成功  扫码返回信息
            getTaskStep(
              {
                resUrl: that.resUrl,
              },
              (res) => {
                if (
                  (res[0].stepNo === 5 || res[0].stepNo === 23) &&
                  res[0].flowType === 2
                ) {
                  // 穿棕/打结
                  openWin("optType", {
                    title: res[0].title,
                    doingResUrl: res[0].doingResUrl,
                    stepId: res[0].id,
                    resId: res[0].resId,
                    stepNo: res[0].stepNo,
                    taskId: res[0].taskId,
                    scanCode: that.scanCode,
                  });
                } else {
                  that.$toast.fail("不能更改");
                }
              }
            );
          } else if (that.flag === 5) {
            // 更改重量
            this.isShow = true;
          }
        });
      } else {
        that.onGetInit();
      }
    },
    // 反转数字
    reverse_a_number(n) {
      n = n + "";
      return n.split("").reverse().join("");
    },
    // 取消登陆
    onClickCancel() {
      window.removeEventListener("keydown", this.onClickKeydown);
      this.no = "";
      this.realName = "";
      this.mobile = "";
      this.pwd = "";
      this.isShow = false;
      this.show = false;
    },
    // 更改重量
    onConfirmWeight() {
      if (this.weight) {
        getGreyClothWeight(
          {
            id: this.greyClothId,
            weight: this.weight,
          },
          () => {
            this.$toast.success("修正成功");
            openWin("index");
          }
        );
      }
    },
    // 打印初始化
    onGetInit() {
      this.printMac = "";
      this.metreMac = "";
      this.pos = {};
      const that = this;
      getInit({}, (res) => {
        let resultArr = eval("(" + res.propertyValue + ")");
        resultArr.forEach((item) => {
          if (item.type == "1") {
            that.printMac = item.mac;
            let posData = item.pos.split(",");
            that.pos = {
              x: Number(posData[0]), // 220
              y: Number(posData[1]), //  30
            };
          } else {
            that.metreMac = item.mac;
          }
        });
      });
    },
    // 更换纱线
    onClickChangeYarn() {},

    // 查询蓝牙状态
    isEnabledBluetooth(status, type, data) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getPrinterStatus(status, type, data);
            } else {
              that.openBluetooth(status, type, data);
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth(status, type, data) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getPrinterStatus(status, type, data);
            }
          } else {
            that.listenBluetoothStatus(status, type, data);
          }
        });
    },
    listenBluetoothStatus(status, type, data) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.getPrinterStatus(status, type, data);
            }
          } else {
            that.$message.error("code: " + err.code + " msg: " + err.msg);
          }
        });
    },

    // 查询打印机状态
    getPrinterStatus(status, type, data) {
      const that = this;
      // that.demo = window.api.require("xGprinterPlus");
      that.demo.getPrinterStatus(function (ret) {
        // alert(JSON.stringify(ret) + "  " + JSON.stringify(err));
        if (ret.status) {
          if (ret.message === "打印机正常") {
            that.getConnectState(status, type, data);
          } else {
            that.connectBleByMacAddress(status, type, data);
          }
        } else {
          that.connectBleByMacAddress(status, type, data);
        }
      });
    },
    // 查询打印机连接状态
    getConnectState(status, type, data) {
      const that = this;
      that.$toast({
        type: "loading",
        message: "查询打印机连接状态",
      });
      // var obj = window.api.require("xGprinterPlus");
      var ret = that.demo.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接  获取打印数据打印
          if (type === 1) {
            if (status === 1) {
              // 接单
              that.onGetTaskAcceptNext();
            } else {
              that.onGetPrintTable();
            }
          } else {
            // 码布打印
            that.onPringLabel(data, status);
          }
        } else {
          // 未连接
          that.$toast({
            type: "error",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress(status, type, data);
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "error",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress(status, type, data);
          },
        });
      }
    },
    // mac 地址连接
    connectBleByMacAddress(status, type, data) {
      const that = this;
      that.$toast({
        type: "loading",
        message: "正在连接，请稍后",
        duration: 20000,
      });
      // var demo = window.api.require("xGprinterPlus");
      that.demo.connectBleByMacAddress(
        {
          macAddress: that.printMac,
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.$toast.clear();
              if (type === 1) {
                if (status === 1) {
                  // 接单
                  that.onGetTaskAcceptNext();
                } else {
                  that.onGetPrintTable();
                }
              } else {
                // 绣字打印
                that.onPringLabel(data, status);
              }
            } else if (ret.message === "连接失败") {
              that.$toast.clear();
              that.$toast.fail("连接失败");
            }
          } else {
            that.$toast.clear();
            that.$toast.fail(err.msg);
          }
        }
      );
    },
    // 码布打印
    onPringLabel(data) {
      const that = this;
      let y1 = [
        that.pos.y,
        that.pos.y + 200,
        that.pos.y + 600,
        that.pos.y + 900,
      ];
      let errorWeight = (
        (Number(data.weight) / Number(data.length)) *
        2
      ).toFixed(2);
      setErrorWeight(errorWeight);
      let demo = window.api.require("xGprinterPlus");
      let rows = [
        {
          lineType: "size",
          width: 30,
          height: 160,
        },
        {
          lineType: "gap",
          data: 2,
        },
        {
          lineType: "direction", //设置打印方向
          direction: "forward", //backward|forward
          mirror: "normal", //normal|mirror
        },
        {
          lineType: "cls", // 清除打印缓冲区
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x,
          y: y1[0],
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "经轴编号：" + data.craftNo,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x,
          y: y1[1],
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "工艺品名：" + data.designNo,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x,
          y: y1[2] + 200,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "色号：" + data.colorNo,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x,
          y: y1[3] + 150,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "批号：" + data.lotNo,
        },

        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 35,
          y: that.pos.y,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "匹号：" + data.designSeqNo,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 35,
          y: that.pos.y + 300,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "织机号: " + data.loomNo,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 35,
          y: that.pos.y + 600,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "落布人：" + data.receiverName,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 35,
          y: that.pos.y + 900,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "落布日期：" + dayjs(data.receiveAt).format("YYYY-MM-DD HH:mm"),
        },

        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "下机门幅: " + data.width,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 190,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "坯布长: " + data.length,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 380,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "坯布重: " + data.weight,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 570,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data:
            "米克重: " +
            parseInt((Number(data.weight) / Number(data.length)) * 1000),
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 760,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "纬密: " + data.latDensity,
        },
        {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 950,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "检验人: " + data.inspectorName,
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 85,
          y: that.pos.y + 1140,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "预计坯布",
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 135,
          y: that.pos.y,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "预计成品克重: " + data.miWeightDesign,
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 135,
          y: that.pos.y + 240,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "刻盘克重: " + data.miWeight,
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 135,
          y: that.pos.y + 460,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "成份含量: " + data.productComposition.replace(/ /g, ""),
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 135,
          y: that.pos.y + 910,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: "入库绣字: " + data.embroideryNo,
        }, {
          lineType: "text", //绘制简体中文
          x: that.pos.x - 135,
          y: that.pos.y,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: data.str,
        },
      ];
      if (data.str2) {
        rows.push({
          lineType: "text", //绘制简体中文
          x: that.pos.x - 185,
          y: that.pos.y,
          rotation: 90, // 0|90|180|270
          xscal: 1, //1~10
          yscal: 1, //1~10
          data: data.str2,
        });
      }
      demo.printLabel(
        {
          rows: rows,
        },
        function (ret, err) {
          if (ret.status) {
            that.$toast({
              type: "success",
              message: "打印成功",
              onClose: () => {
                openWin("index");
              },
            });
          } else {
            that.$toast.fail("打印异常,请重试" + err.msg);
          }
        }
      );
    },
    // 断开连接
    disConnect(status) {
      const that = this;
      // var demo = window.api.require("xGprinterPlus");
      that.demo.disConnect(function (ret, err) {
        if (ret.status) {
          that.$toast({
            type: "fail",
            message: "已断开连接",
            onClose: () => {
              if (status === 1) {
                // 接单
                that.onGetTaskAccept(that.params);
              } else {
                // 已接单
                openWin("warping", that.params);
              }
            },
          });
        } else {
          that.$toast.fail(err.msg);
        }
      });
    },
    // 获取下一流程 (暂未接单)
    onGetTaskAcceptNext() {
      const that = this;
      getTaskStep(
        {
          resUrl: that.params.qrCode,
        },
        (res) => {
          that.doingResUrl = res[0].doingResUrl;
          // 报工
          that.params = {
            stepId: res[0].id,
            flowType: res[0].flowType,
            resId: res[0].resId,
            stepNo: res[0].stepNo,
            taskId: res[0].taskId,
            resUrl: res[0].resUrl,
            nextResUrl: res[0].doingResUrl,
            nextStepNo: res[0].nextStepNo,
            todoResUrl: res[0].todoResUrl,
            doingResUrl: res[0].doingResUrl,
            stepName: res[0].stepName,
            nextStepName: res[0].nextStepName,
          };
          getTaskAcceptNext(
            {
              resUrl:
                process.env.VUE_APP_YARN_URL +
                that.params.todoResUrl +
                "/" +
                that.params.resId,
            },
            (res) => {
              that.subResIds.splice(0, that.subResIds.length);
              if(res.newFlag) {
                loadWeavingCraftDetailByCraftData({
                  craftId: res.id
                }, data => {
                  const craftDetails = data.filter(craftDetail => !craftDetail.lonOnly);
                  if(craftDetails.length == 0) {
                    that.$toast.fail("盘头下没有确认纬纱的盘头详情");
                    return;
                  }
                  const totalNum = craftDetails.map(craftDetail => Number(craftDetail.remainNum)).reduce((a, b) => Number(a) + Number(b));
                  for(let i=0; i<totalNum; i++) {
                    that.subResIds.push("0");
                  }
                  // 接单
                  that.onGetTaskAccept(that.params);
                });
              } else {
                if (res.craftNum) {
                  for (let i = 0; i < res.craftNum; i++) {
                    that.subResIds.push("0");
                  }
                }
                // 接单
                that.onGetTaskAccept(that.params);
              }
            }
          );
        }
      );
    },
    onGetPrintTable() {
      const that = this;
      getTaskAcceptNext(
        {
          resUrl:
            process.env.VUE_APP_YARN_URL +
            that.doingResUrl +
            "/" +
            that.params.resId,
        },
        () => {
          // that.printLen = 0;
          // res.unshift({});
          // that.printData(res);
          that.$toast({
            type: "success",
            message: "落布流程发起成功",
            duration: 1000,
            onClose: () => {
              // that.isEnabledBluetooth(true);
              // 接单成功
              window.api.closeToWin({ name: "warping" });
              // 跳转首页
              openWin("index");
            },
          });
        }
      );
    },
    printData(res) {
      const that = this;
      that.$toast.loading({
        message: "正在打印",
        forbidClick: true,
        duration: 20000,
        loadingType: "spinner",
      });
      res.forEach((item, i) => {
        if (item.printFlag == 0) {
          that.printLen++;
          let url = "";
          if (item.qrCode.indexOf("list_to_do_4_worker_from_res") != -1) {
            url = item.id;
          } else {
            url =
              item.qrCode +
              "?taskId=" +
              item.taskId +
              "&craftId=" +
              item.craftId +
              "&craftNo=" +
              item.craftNo;
          }
          let rows = [
            {
              lineType: "size",
              width: 35,
              height: 25,
            },
            {
              lineType: "gap",
              data: 2,
            },
            {
              lineType: "direction", //设置打印方向
              direction: "forward", //backward|forward
              mirror: "normal", //normal|mirror
            },
            {
              lineType: "cls", // 清除打印缓冲区
            },
            {
              lineType: "text", //绘制简体中文
              x: 80,
              y: 30,
              rotation: 90, // 0|90|180|270
              xscal: 1, //1~10
              yscal: 3, //1~10
              data: "",
            },
          ];
          if (i >= 0) {
            rows = [
              {
                lineType: "size",
                width: 35,
                height: 25,
              },
              {
                lineType: "gap",
                data: 2,
              },
              {
                lineType: "direction", //设置打印方向
                direction: "forward", //backward|forward
                mirror: "normal", //normal|mirror
              },
              {
                lineType: "cls", // 清除打印缓冲区
              },
              {
                lineType: "text", //绘制简体中文
                x: 80,
                y: 30,
                rotation: 90, // 0|90|180|270
                xscal: 1, //1~10
                yscal: 1, //1~10
                data: item.designNo,
              },
              {
                lineType: "text", //绘制简体中文
                x: 40,
                y: 30,
                rotation: 90, // 0|90|180|270
                xscal: 1, //1~10
                yscal: 1, //1~10
                data:
                  item.taskId +
                  "_" +
                  item.craftNo +
                  +"_" +
                  "[" +
                  res.length +
                  "_" +
                  (i + 1) +
                  "]",
              },
              {
                lineType: "qrcode", // 绘制qrcode
                x: 100,
                y: 20,
                level: "L", //L|M|H|Q
                cellwith: 4,
                rotation: 0, // 0|90|180|270
                data: url,
              },
            ];
          }
          let obj = window.api.require("xGprinterPlus");
          obj.printLabel(
            {
              rows: rows,
            },
            function (ret, err) {
              that.$toast.clear();
              if (ret.status) {
                that.$toast.success("打印成功，请取走二维码");
              } else {
                that.$toast.fail("打印异常" + err.msg);
              }
            }
          );
        }
      });
      let ms = that.printLen * 2 * 1000;
      setTimeout(() => {
        openWin("index");
      }, ms);
      if (that.printLen == 0) {
        that.$toast.fail("没有需要补打印的数据");
        return false;
      }
    },
    // 接单
    onGetTaskAccept(res) {
      const that = this;
      let obj = {
        stepNo: that.params.stepNo,
        taskId: that.params.taskId,
      };
      if (that.params.stepNo === 16) {
        obj.subResIds = that.subResIds;
        obj.stepId = that.params.stepId;
        getTaskAccept(obj, () => {
          // 打印
          that.onGetPrintTable();
        });
      } else {
        getTaskAccept(obj, () => {
          // 已接单
          if (res.flowType === 3 && res.stepNo === 3) {
            // 验布
            openWin("checkCloth", that.params);
          } else {
            if (
              that.params.flowType === 2 &&
              (that.params.stepNo === 2 ||
                that.params.stepNo === 4 ||
                that.params.stepNo === 6 ||
                that.params.stepNo === 11 ||
                that.params.stepNo === 15 ||
                that.params.stepNo === 21 ||
                that.params.stepNo === 22)
            ) {
              openWin("group-leader", that.params);
            } else {
              openWin("warping", that.params);
            }
          }
        });
      }
    },
    // 修布直接打印落布信息
    onClickPrint() {
      const that = this;
      getTaskStep(
        {
          resUrl:
            process.env.VUE_APP_YARN_URL +
            that.params.doingResUrl +
            "/" +
            that.params.taskId,
        },
        (doingUrl) => {
          getWeavingClothByStepNo(
            {
              taskId: that.params.taskId,
              stepNo: 3,
            },
            (resUrl) => {
              that.str = "";
              let resultArr = eval("(" + resUrl.items[0].value + ")");
              resultArr.forEach((item) => {
                item.items.forEach((m) => {
                  if (m.originalValue) {
                    that.str += m.label + ": " + m.originalValue;
                  }
                });
              });
              if (that.str.length < 82) {
                doingUrl.str = that.str;
              } else {
                doingUrl.str = that.str.substr(0, 82);
                doingUrl.str2 = that.str.substr(82, 164);
              }
              // 连接打印
              that.$toast({
                type: "loading",
                message: "查询打印机连接状态",
              });
              let obj = window.api.require("xGprinterPlus");
              let ret = obj.getConnectState();
              if (ret.status) {
                let result = false;
                ret.state.forEach((bool) => {
                  if (bool) {
                    result = bool;
                  }
                });
                if (result) {
                  // 已连接  获取打印数据打印
                  that.onPringLabel(doingUrl);
                } else {
                  // 未连接
                  that.$toast({
                    type: "error",
                    message: "未连接, 请等待",
                    duration: 1500,
                    onClose: () => {
                      that.connectBleByMacAddress2(doingUrl, true);
                    },
                  });
                }
              } else {
                // 未连接
                that.$toast({
                  type: "error",
                  message: "未连接, 请等待",
                  duration: 1500,
                  onClose: () => {
                    that.connectBleByMacAddress2(doingUrl, true);
                  },
                });
              }
            }
          );
        }
      );
    },
    connectBleByMacAddress2(data, status) {
      const that = this;
      if (status) {
        that.$toast({
          type: "loading",
          message: "正在连接，请稍后",
          duration: 20000,
        });
      }
      let demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: that.printMac
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.$toast.clear();
              // 码布打印
              if (status) {
                that.onPringLabel(data);
              }
            } else if (ret.message === "连接失败") {
              that.$toast.fail("连接失败");
            }
          } else {
            that.$toast.fail(err.msg);
          }
        }
      );
    },
    // 环节历史数据
    onClickRight() {
      getTaskStepList(
        {
          depId: 44,
          taskId: this.taskId,
          pageSize: 100,
          pageNum: 1,
        },
        (res) => {
          openWin("historical", {
            tableData: res.list,
            title: "",
            loomNo: this.loomNo,
            taskId: this.taskId,
          });
        }
      );
    },
  },
};
</script>

<style scoped lang="scss">
.login {
  display: flex;
  flex-direction: column;

  .login-cell {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding: 30px;
  }

  // .van-button {
  //   width: 246px;
  //   height: 90px;
  //   background: #ffffff;
  //   border: 1px solid #1677ff;
  //   border-radius: 4px;
  //   font-size: 28px;
  //   color: #1677ff;
  //   margin-right: 15px;
  //   margin-bottom: 15px;
  //   .van-button__text {
  //     display: flex;
  //     flex-direction: column;
  //   }
  // }
  .login-btn {
    width: 100%;
    height: calc(100vh - 140px);
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .login-btn__logo {
      width: 90%;
      flex: 1;
      display: flex;
      flex-wrap: nowrap;
      justify-content: space-around;
      overflow: hidden;
      .van-cell-group {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        position: relative;
        padding: 0 50px;
        .van-button {
          padding: 0 30px;
          background-color: #07c160;
          border-color: #07c160;
          color: #fff;
          font-weight: 800;
          &.active {
            background-color: #e6a23c;
            border-color: #e6a23c;
            animation: fade 1500ms infinite;
          }
          &.finish {
            background-color: #f56c6c;
            border-color: #f56c6c;
          }
        }
        .line0 {
          position: absolute;
          top: 47%;
          left: 0;
          display: flex;
          width: 50px;
          height: 230px;
          margin-top: -100px;
          border: 1px solid grey;
          border-right: none;
        }
        .line1 {
          position: absolute;
          top: 50%;
          right: -50px;
          display: flex;
          width: 50px;
          height: 2px;
          background: grey;
        }
        .line2 {
          position: absolute;
          top: 47%;
          right: 0;
          display: flex;
          width: 50px;
          height: 230px;
          margin-top: -100px;
          border: 1px solid grey;
          border-left: none;
        }
        &:last-child {
          .line1 {
            background: #fff;
          }
        }
      }
    }
    .login-btn__login {
      width: 480px;
      height: 80px;
      margin: 20px;
      background: #07c160;
      border-color: #07c160;
      border-radius: 2px;
      font-size: 32px;
      color: #ffffff;
      position: relative;
      z-index: 300;
    }
    .home-input {
      width: 470px;
      height: 80px;
      line-height: 80px;
      // position: absolute;
      // bottom: 20px;
      // z-index: 120;
    }
  }
}
</style>

<style lang="scss">
.login {
  .van-nav-bar__left {
    i {
      display: flex;
      align-items: center;
      font-size: 20px;
    }
    .van-button {
      margin-left: 15px;
    }
  }
  .van-nav-bar__right {
    .van-button {
      display: flex !important;
      align-items: center;
      span {
        font-size: 20px;
      }
      margin-right: 20px;
      &:last-child {
        margin-left: 0;
      }
      &:nth-child(2) {
        background: #07c160;
        border-color: #07c160;
      }
    }
  }
  .public-scroll {
    height: calc(100vh - 100px);
  }
  .van-dialog__content {
    margin: 40px 0;
  }
}
@keyframes fade {
  from {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}
</style>
